<template>

  <div class="app-container">
    <el-container>
      <el-header>
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="网站A" class="mt-form-item-left">
            <el-select v-model="searchForm.website_A_selected_website" clearable @change="handleWebsiteAChange">
              <el-option
                v-for="item in searchForm.website_list"
                :key="item.id"
                v-loading="websiteLoading"
                :label="item.domain"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目录A" class="mt-form-item-left">
            <el-select
              v-model="searchForm.website_A_selected_category"
              v-loading="categoryALoading"
              clearable
              filterable
              @change="checkSelection"
            >
              <el-option
                v-for="(item,index) in searchForm.website_A_categories"
                :key="index"
                :label="'[' + item.product_count + ']' + item.category_name"
                :value="item.category_name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="网站B" class="mt-form-item-left">
            <el-select v-model="searchForm.website_B_selected_website" clearable @change="handleWebsiteBChange">
              <el-option
                v-for="item in searchForm.website_list"
                :key="item.id"
                v-loading="websiteLoading"
                :label="item.domain"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目录B" class="mt-form-item-left">
            <el-select
              v-model="searchForm.website_B_selected_category"
              v-loading="categoryBLoading"
              clearable
              filterable
            >
              <el-option
                v-for="(item,index) in searchForm.website_B_categories"
                :key="index"
                :label="'[' + item.product_count + ']' + item.category_name"
                :value="item.category_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>

            <el-button type="primary" :disabled="compare_disable" :loading="listLoading" @click="handleClickCompare">
              对比
            </el-button>

            <el-popover
              placement="bottom"
              trigger="hover"
              width="300"
              content="网站A 是产品源, 目录A 必选;
                网站B (一般选取为 内部站点 如 coosfly.com) 是将要产品上传的目标站点, 当目录B 为空则对比全站"
            >
              <i slot="reference" class="el-icon-question" />
            </el-popover>

          </el-form-item>
        </el-form>
      </el-header>
      <el-container :style="styleObject">
        <el-aside width="280px">
          <H1>产品</H1>
        </el-aside>
        <el-container>
          <el-main>
            <div :gutter="10">
              <el-col>
                <div style="display: flex;flex-direction: row-reverse;margin: 10px">
                  <el-button size="mini" style="margin-left: 10px;margin-right: 10px" @click="location2export">
                    产品导出
                  </el-button>
                  <el-dropdown trigger="click" size="mini">
                    <el-button
                      type="danger"
                      :loading="listLoading"
                      :disabled="!checkedIds.length"
                    >
                      批量上传<i class="el-icon-arrow-down el-icon--right" />
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        v-for="(item, index) in multiOptions"
                        :key="index"
                        :title="'To:' + item.target"
                        @click.native.stop="handleClickUpload('multi', item.web_id, item.type)"
                      >
                        {{ item.label }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <el-button size="mini" style="margin-right: 10px" @click="handleSelectAll">全选/取消
                  </el-button>
                  <el-button size="mini" type="primary" style="margin-right: 80px" @click="handleClickFilter">筛选
                  </el-button>
                  <el-row>
                    <el-col :span="11">
                      <el-input v-model.number="min" placeholder="最小相似度" clearable />
                    </el-col>
                    <el-col class="line" :span="2" style="text-align: center;line-height: 40px;">-</el-col>
                    <el-col :span="11">
                      <el-input v-model.number="max" placeholder="最大相似度" clearable />
                    </el-col>
                  </el-row>
                </div>

                <el-row v-loading="listLoading" :gutter="20">
                  <el-col v-for="item in data" :key="item.id" :xl="8" :lg="12" :md="12">
                    <el-card :body-style="{ padding: '0px' }" shadow="hover" class="mt-card">
                      <div slot="header" class="clearfix mt-card-top">
                        <el-checkbox v-model="item.checked" @change="handleSelectSingle" />

                        <span><el-tag
                          type="danger"
                          style="margin-left: 10px"
                          size="mini"
                        >相似度{{ item.score }}</el-tag></span>
                        <div class="mt-card-top-right">
                          <el-button
                            type="success"
                            size="mini"
                            :disabled="!item.productB.id"
                          >相同
                          </el-button>
                          <el-button type="primary" plain size="mini" :disabled="!item.rdata">
                            相似列表
                          </el-button>
                        </div>
                      </div>
                      <el-row :gutter="20">
                        <el-col :span="12" class="mt-col">
                          <span class="mt-website" :title="item.productA.domain">网站A:{{ item.productA.domain }}</span>
                          <img :src="item.productA.image" :alt="item.productA.title" class="mt-img">
                          <span style="font-size: 12px">产品id: {{ item.productA.id }}</span>
                          <el-button
                            type="primary"
                            size="mini"
                            :loading="listLoading"
                            class="mt-upload-btn"
                            :title="'将该产品上传到'+item.productB.domain"
                            @click="handleClickUpload('single', item.productB.web_id, [item.id], 'a2b')"
                          >上传
                          </el-button>
                          <!--<el-dropdown trigger="click">-->
                          <!--<el-button type="primary" size="mini" :loading="listLoading" class="mt-upload-btn">-->
                          <!--产品上传<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
                          <!--</el-button>-->
                          <!--<el-dropdown-menu slot="dropdown">-->
                          <!--<el-dropdown-item v-for="item in websites" :key="item.id"-->
                          <!--@click.native.stop="handleShowUploadCategoryDialog(item)"-->
                          <!--:disabled="item.type !== 'PrestaShop'">{{item.domain}}-->
                          <!--</el-dropdown-item>-->
                          <!--</el-dropdown-menu>-->
                          <!--</el-dropdown>-->
                        </el-col>
                        <el-col v-if="item.productB.id" :span="12" class="mt-col">
                          <span class="mt-website" :title="item.productB.domain">网站B:{{ item.productB.domain }}</span>
                          <img :src="item.productB.image" :alt="item.productB.title" class="mt-img">
                          <span style="font-size: 12px">产品id: {{ item.productB.id }}</span>
                          <el-button
                            type="primary"
                            size="mini"
                            :loading="listLoading"
                            class="mt-upload-btn"
                            :title="'将该产品上传到'+item.productA.domain"
                            @click="handleClickUpload('single', item.productA.web_id, [item.id], 'b2a')"
                          >上传
                          </el-button>
                          <!--<el-dropdown trigger="click">-->
                          <!--<el-button type="primary" size="mini" title="上传" @click="handleClickUpload('single')"-->
                          <!--:loading="listLoading" class="mt-upload-btn">-->
                          <!--产品上传<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
                          <!--</el-button>-->
                          <!--<el-dropdown-menu slot="dropdown">-->
                          <!--<el-dropdown-item v-for="item in websites" :key="item.id"-->
                          <!--@click.native.stop="handleShowUploadCategoryDialog(item)"-->
                          <!--:disabled="item.type !== 'PrestaShop'">{{item.domain}}-->
                          <!--</el-dropdown-item>-->
                          <!--</el-dropdown-menu>-->
                          <!--</el-dropdown>-->
                        </el-col>
                      </el-row>
                    </el-card>
                  </el-col>
                </el-row>
              </el-col>
            </div>
          </el-main>
          <el-footer height="30px" style="margin-bottom: 20px">
            <el-pagination
              v-if="data.length"
              background
              class="mt-pagination"
              :current-page="page"
              :page-sizes="[15,60,90,150]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </el-footer>
        </el-container>
      </el-container>
    </el-container>

  </div>
</template>

<script>
import { GetWebs, add_crawl_product_to_task, GetWebCategory } from '@/api/erp/crawlproduct'
import { show_products_compare } from '@/api/erp/compare'
import { Get as GetWebsite } from '@/api/erp/elicink/website'

export default {
  data() {
    return {
      styleObject: {
        height: document.documentElement.clientHeight - 150 + 'px'
      },

      listLoading: false,
      websiteLoading: false,
      categoryALoading: false,
      categoryBLoading: false,
      searchForm: {
        website_list: [],
        website_A_selected_website: null,
        website_B_selected_website: null,

        website_A_selected_category: null,
        website_B_selected_category: null,

        website_A_categories: [],
        website_B_categories: []
      },
      compare_disable: true,

      min: null,
      max: null,
      websites: [],
      multiOptions: [],
      // pagination
      pagesize: 15,
      page: 1,
      total: 0,

      data: [],
      checkedIds: []

    }
  },
  computed: {
    website_A_selected_website: function() {
      return this.$route.query.wa && parseInt(this.$route.query.wa) || null
    },
    website_A_selected_category: function() {
      return this.$route.query.ca || null
    },
    website_B_selected_website: function() {
      return this.$route.query.wb && parseInt(this.$route.query.wb) || null
    },
    website_B_selected_category: function() {
      return this.$route.query.cb || null
    }
  },
  mounted() {
    // 动态设置背景图的高度为浏览器可视区域高度

    // 首先在Virtual DOM渲染数据时，设置下背景图的高度．
    this.styleObject.height = `${document.documentElement.clientHeight - 150}px`
    // 然后监听window的resize事件．在浏览器窗口变化时再设置下背景图高度．
    const that = this
    window.onresize = function temp() {
      that.clientHeight = `${document.documentElement.clientHeight - 150}px`
    }
  },
  created() {
    this.handleFetchWebsites()
    GetWebsite().then(response => {
      this.websites = response.data.data
    })
    this.searchForm.website_A_selected_website = this.website_A_selected_website || null
    this.searchForm.website_A_selected_category = this.website_A_selected_category || null
    this.searchForm.website_B_selected_website = this.website_B_selected_website || null
    this.searchForm.website_B_selected_category = this.website_B_selected_category || null

    if (this.website_A_selected_website && this.website_A_selected_category && this.website_B_selected_website) {
      this.handleFetchCompareResult()
    }
  },
  methods: {
    checkSelection(v) {
      this.compare_disable = !(this.searchForm.website_A_selected_website && this.searchForm.website_B_selected_website && this.searchForm.website_A_selected_category)
    },
    handleFetchWebsites() {
      GetWebs()
        .then(response => {
          this.searchForm.website_list = response.data
          this.handleWebsiteAChange(this.website_A_selected_website, true)
          this.handleWebsiteBChange(this.website_B_selected_website, true)
        })
    },
    handleClickCompare() {
      this.page = 1
      this.handleFetchCompareResult()
    },
    handleClickFilter() {
      this.page = 1
      this.handleFetchCompareResult()
    },
    handleFetchCompareResult() {
      this.listLoading = true
      show_products_compare({
        pagesize: this.pagesize,
        page: this.page,
        website_A: this.searchForm.website_A_selected_website,
        category_A: this.searchForm.website_A_selected_category,
        website_B: this.searchForm.website_B_selected_website,
        category_B: this.searchForm.website_B_selected_category,
        min: this.min,
        max: this.max
      }).then(response => {
        this.checkedIds = []
        if (response.message) {
          this.$notify({
            title: '成功',
            message: response.message,
            type: 'success',
            duration: 2000
          })
          this.listLoading = false
          this.data = []
          this.multiOptions = []
          return
        }
        this.data = response.data.data.map(v => {
          this.$set(v, 'checked', false)
          return v
        })
        this.total = response.data.total

        if (this.data.length) {
          const first = this.data[0]
          this.multiOptions = [
            {
              web_id: first.productB.web_id,
              label: '左侧产品上传到右侧站点',
              type: 'a2b',
              target: first.productB.domain
            },
            {
              web_id: first.productA.web_id,
              label: '右侧产品上传到左侧站点',
              type: 'b2a',
              target: first.productA.domain
            }
          ]
        }
        this.listLoading = false
        window.scrollTo(0, 0)
      }).catch(e => {
        this.listLoading = false
      })
    },
    handleSelectAll() {
      const _total = this.data.length
      const _checked_length = this.data.filter(m => m.checked).length
      if (_checked_length) {
        if (_checked_length < _total) {
          this.checkedIds = this.data.map(m => {
            m.checked = true
          })
        } else {
          this.data.map(m => {
            m.checked = false
          })
          this.checkedIds = []
        }
      } else {
        this.data.map(m => {
          m.checked = true
        })
        this.checkedIds = this.data.map(m => m.id)
      }
    },
    handleSelectSingle() {
      this.checkedIds = this.data.filter(m => m.checked).map(m => m.id)
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.handleFetchCompareResult()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.handleFetchCompareResult()
    },
    handleWebsiteAChange(v, init) {
      if (v) {
        if (!(init)) this.searchForm.website_A_selected_category = null

        this.categoryALoading = true
        GetWebCategory(null, `only_name=1&web=${this.searchForm.website_A_selected_website}`)
          .then(response => {
            this.searchForm.website_A_categories = response.data
            this.categoryALoading = false
          }).catch(e => {
            this.categoryALoading = false
          })
      }
      this.checkSelection()
    },
    handleWebsiteBChange(v, init) {
      if (v) {
        if (!(init)) this.searchForm.website_B_selected_category = null

        this.categoryBLoading = true
        GetWebCategory(null, `only_name=1&web=${this.searchForm.website_B_selected_website}`)
          .then(response => {
            this.searchForm.website_B_categories = response.data
            this.categoryBLoading = false
          }).catch(e => {
            this.categoryBLoading = false
          })
      }
      this.checkSelection()
    },
    handleClickUpload(action, web_id, type, items) {
      switch (action) {
        case 'single': {
          this.handleSelectWebsiteUpload(web_id, items, type)
          break
        }
        case 'multi': {
          this.handleSelectWebsiteUpload(web_id, this.checkedIds, type, true)
          break
        }
      }
    },
    // 选择站点上传
    handleSelectWebsiteUpload(web_id, items, type, multi) {
      this.listLoading = true
      add_crawl_product_to_task(JSON.stringify({
        web_id: web_id,
        items: items,
        type: type
      })).then(response => {
        this.listLoading = false
        this.$notify({
          title: '成功',
          message: response.message,
          type: 'success',
          duration: 4000
        })
        if (multi) {
          this.checkedIds = []
          this.data.map(m => {
            m.checked = false
          })
        }
      }).catch(e => {
        this.listLoading = false
      })
    },
    location2export() {
      const link = this.$router.resolve({
        name: 'erp.productExport2',
        params: {
          src: 'crawl',
          process_type: '1'
        }
      })
      window.open(link.href, '_self')
    }// methods end
  }
}
</script>

<style scoped>

  .clearfix:before,
  .clearfix:after {
    display: block;
    content: '';
    clear: both;
    height: 0;
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .top {
    margin: 20px;
  }

  .top >>> .el-tag + .el-tag {
    margin-left: 10px;
  }

  .fixed {
    position: fixed;
    top: 140px;
    overflow-y: scroll;
    height: calc(100% - 264px);
  }

  .fixed::-webkit-scrollbar { /*滚动条整体样式*/
    width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  .fixed::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #F90;
    background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent);
  }

  .fixed::-webkit-scrollbar-track { /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    /*border-radius: 10px;*/
    background: #EDEDED;
  }

  .mt-form-item-left {
    width: 23%;
    margin-right: 0;
  }

  .el-form-item {
    margin-bottom: 1px;
  }

  .mt-form-item-left >>> .el-form-item__content {
    width: calc(100% - 68px);
  }

  .mt-form-item-left >>> .el-select {
    width: 100%;
  }

  div.is-hover-shadow:hover {
    border-color: #DCDFE6;
  }

  .mt-form-item-search >>> .el-form-item__content {
    width: 100%;
  }

  .mt-card {
    margin: 0 auto;
    margin-top: 20px;
  }

  .mt-col {
    text-align: center;
  }

  .mt-upload-btn {
    width: 200px;
    margin: 10px auto;
  }

  .mt-img {
    width: 200px;
    height: 280px;
    margin: 5px 0 auto;
  }

  .mt-card-top {
    margin: 0 auto;
  }

  .mt-card-top-right {
    float: right;
  }

  .mt-website {
    color: #909399;
    font-size: xx-small;
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin: 4px;
  }

</style>
